package com.vehiclemanagement.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vehiclemanagement.annotation.OperationLogAnnotation;
import com.vehiclemanagement.entity.Vehicle;
import com.vehiclemanagement.service.VehicleService;
import com.vehiclemanagement.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.io.ByteArrayOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.math.BigDecimal;

/**
 * 车辆管理控制器
 */
@RestController
@RequestMapping("/vehicle")
public class VehicleController {
    
    @Autowired
    private VehicleService vehicleService;
    
    /**
     * 分页查询车辆列表
     */
    @GetMapping("/list")
    public R<IPage<Vehicle>> list(
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "searchTerm", required = false) String searchTerm,
            @RequestParam(value = "vehicleType", required = false) String vehicleType,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "includeDeleted", required = false) Boolean includeDeleted,
            @RequestParam(value = "orderBy", required = false) String orderBy,
            @RequestParam(value = "orderType", required = false) String orderType,
            @RequestParam(value = "orderFieldsJson", required = false) String orderFieldsJson) {
        
        System.out.println("接收到查询请求，单字段排序参数: " + orderBy + " " + orderType);
        System.out.println("接收到查询请求，多字段排序参数: " + orderFieldsJson);
        
        // 处理多字段排序
        if (orderFieldsJson != null && !orderFieldsJson.isEmpty()) {
            try {
                System.out.println("开始处理多字段排序参数: " + orderFieldsJson);
                // 多字段排序的处理逻辑将在Service层实现
                IPage<Vehicle> result = vehicleService.pageVehiclesWithMultiSort(current, size, searchTerm, vehicleType, status, includeDeleted, orderFieldsJson);
                System.out.println("多字段排序查询完成，返回记录数: " + (result != null ? result.getRecords().size() : 0));
                return R.ok(result);
            } catch (Exception e) {
                System.err.println("解析多字段排序参数失败: " + e.getMessage());
                e.printStackTrace();
                // 如果解析失败，回退到单字段排序
            }
        }
        
        IPage<Vehicle> page;
        if (orderBy != null && !orderBy.isEmpty()) {
            // 使用带排序的方法
            page = vehicleService.pageVehicles(current, size, searchTerm, vehicleType, status, includeDeleted, orderBy, orderType);
        } else {
            // 使用不带排序的方法
            page = vehicleService.pageVehicles(current, size, searchTerm, vehicleType, status, includeDeleted);
        }
        
        return R.ok(page);
    }

    /**
     * 导出车辆数据为Excel
     */
    @GetMapping("/list/download")
    @OperationLogAnnotation(module = "车辆管理", operationType = 5, description = "导出车辆数据")
    public ResponseEntity<Resource> exportVehicles(
            @RequestParam(value = "searchTerm", required = false) String searchTerm,
            @RequestParam(value = "vehicleType", required = false) String vehicleType,
            @RequestParam(value = "status", required = false) Integer status) {
        
        System.out.println("接收到导出请求: searchTerm=" + searchTerm + ", vehicleType=" + vehicleType + ", status=" + status);
        
        try {
            // 获取符合条件的所有车辆数据
            List<Vehicle> vehicles = vehicleService.getAllVehiclesForExport(searchTerm, vehicleType, status);
            
            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("车辆数据");
            
            // 创建标题行样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] columns = {"ID", "车牌号", "车辆类型", "品牌", "型号", "颜色", "购买日期", "登记日期", "状态"};
            for (int i = 0; i < columns.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(columns[i]);
                cell.setCellStyle(headerStyle);
            }
            
            // 填充数据
            int rowNum = 1;
            for (Vehicle vehicle : vehicles) {
                Row row = sheet.createRow(rowNum++);
                
                // ID列
                if (vehicle.getId() != null) {
                    row.createCell(0).setCellValue(vehicle.getId().toString());
                } else {
                    row.createCell(0).setCellValue("");
                }
                
                // 车牌号
                row.createCell(1).setCellValue(vehicle.getPlateNumber() != null ? vehicle.getPlateNumber() : "");
                
                // 车辆类型
                row.createCell(2).setCellValue(vehicle.getVehicleType() != null ? vehicle.getVehicleType() : "");
                
                // 品牌
                row.createCell(3).setCellValue(vehicle.getBrand() != null ? vehicle.getBrand() : "");
                
                // 型号
                row.createCell(4).setCellValue(vehicle.getModel() != null ? vehicle.getModel() : "");
                
                // 颜色
                row.createCell(5).setCellValue(vehicle.getColor() != null ? vehicle.getColor() : "");
                
                // 处理日期 - 购买日期
                row.createCell(6).setCellValue(vehicle.getPurchaseDate() != null ? vehicle.getPurchaseDate().toString() : "");
                
                // 登记日期 - 由于Vehicle实体中没有registrationDate字段，使用创建时间代替
                row.createCell(7).setCellValue(vehicle.getCreateTime() != null ? vehicle.getCreateTime().toString() : "");
                
                // 处理状态
                String statusText = "";
                if (vehicle.getStatus() != null) {
                    switch (vehicle.getStatus()) {
                        case 0: statusText = "报废"; break;
                        case 1: statusText = "正常使用"; break;
                        case 2: statusText = "维修中"; break;
                        case 3: statusText = "停用"; break;
                        default: statusText = "未知状态"; break;
                    }
                }
                row.createCell(8).setCellValue(statusText);
            }
            
            // 自动调整列宽
            for (int i = 0; i < columns.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 将工作簿写入字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();
            
            // 生成文件名
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
            String timestamp = LocalDateTime.now().format(formatter);
            String filename = "vehicles_" + timestamp + ".xlsx";
            
            // 返回Excel文件
            ByteArrayResource resource = new ByteArrayResource(outputStream.toByteArray());
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
                    .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                    .contentLength(resource.contentLength())
                    .body(resource);
            
        } catch (IOException e) {
            System.err.println("导出车辆数据失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取车辆详情
     */
    @GetMapping("/{id}")
    public R<Vehicle> getById(@PathVariable Long id) {
        Vehicle vehicle = vehicleService.getVehicleById(id);
        if (vehicle == null) {
            return R.error("车辆不存在");
        }
        return R.ok(vehicle);
    }
    
    /**
     * 添加车辆
     */
    @PostMapping
    @OperationLogAnnotation(module = "车辆管理", operationType = 2, description = "添加车辆")
    public R<Boolean> add(@RequestBody Vehicle vehicle) {
        System.out.println("接收到添加车辆请求，数据：" + vehicle);
        
        // 检查必要字段
        if (vehicle.getPlateNumber() == null || vehicle.getPlateNumber().trim().isEmpty()) {
            return R.error("车牌号不能为空");
        }
        if (vehicle.getVehicleType() == null || vehicle.getVehicleType().trim().isEmpty()) {
            return R.error("车辆类型不能为空");
        }
        if (vehicle.getBrand() == null || vehicle.getBrand().trim().isEmpty()) {
            return R.error("品牌不能为空");
        }
        
        // 检查车牌号是否已存在（未删除状态）
        if (vehicleService.existsActiveVehicleWithPlateNumber(vehicle.getPlateNumber())) {
            return R.error("添加失败：车牌号 " + vehicle.getPlateNumber() + " 已存在且未被删除，不能重复添加");
        }
        
        boolean result = vehicleService.addVehicle(vehicle);
        if (result) {
            return R.ok(true);
        } else {
            System.out.println("添加车辆失败，服务层返回false");
            return R.error("添加失败，请检查车牌号是否已存在");
        }
    }
    
    /**
     * 更新车辆
     */
    @PutMapping
    @OperationLogAnnotation(module = "车辆管理", operationType = 3, description = "更新车辆")
    public R<Boolean> update(@RequestBody Vehicle vehicle) {
        if (vehicle.getId() == null) {
            return R.error("车辆ID不能为空");
        }
        boolean result = vehicleService.updateVehicle(vehicle);
        return result ? R.ok(true) : R.error("更新失败");
    }
    
    /**
     * 删除车辆（物理删除）
     */
    @DeleteMapping("/{id}")
    @OperationLogAnnotation(module = "车辆管理", operationType = 4, description = "删除车辆")
    public R<Boolean> delete(@PathVariable Long id) {
        System.out.println("接收到删除车辆请求，ID: " + id);
        
        boolean result = vehicleService.deleteVehicle(id);
        
        if (result) {
            System.out.println("成功删除车辆，ID: " + id);
            return R.ok(true);
        } else {
            System.out.println("删除车辆失败，ID: " + id);
            return R.error("删除失败");
        }
    }
    
    /**
     * 获取车辆类型列表
     */
    @GetMapping("/types")
    public R<List<String>> getVehicleTypes() {
        List<String> types = vehicleService.getVehicleTypes();
        return R.ok(types);
    }
    
    /**
     * 测试接口
     */
    @GetMapping("/test")
    public R<String> test() {
        return R.ok("车辆管理API正常运行！");
    }
    
    /**
     * 获取可用车辆列表
     */
    @GetMapping("/available")
    public R<List<Vehicle>> available() {
        // 获取状态为0(空闲)的车辆
        List<Vehicle> vehicles = vehicleService.getAvailableVehicles();
        return R.ok(vehicles);
    }
    
    /**
     * 下载车辆导入模板
     */
    @GetMapping("/import/template")
    @OperationLogAnnotation(module = "车辆管理", operationType = 5, description = "下载车辆导入模板")
    public ResponseEntity<Resource> downloadImportTemplate() {
        System.out.println("接收到下载车辆导入模板请求");
        
        try {
            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("车辆导入模板");
            
            // 创建标题行样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] columns = {"车牌号*", "车辆类型*", "品牌*", "型号", "颜色", "位置", "车架号", "发动机号", "购买价格", "当前里程", "购买日期", "登记日期", "保险到期日", "年检到期日", "状态*", "备注"};
            for (int i = 0; i < columns.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(columns[i]);
                cell.setCellStyle(headerStyle);
            }
            
            // 创建示例数据行
            Row exampleRow = sheet.createRow(1);
            exampleRow.createCell(0).setCellValue("粤B12345");
            exampleRow.createCell(1).setCellValue("轿车");
            exampleRow.createCell(2).setCellValue("丰田");
            exampleRow.createCell(3).setCellValue("卡罗拉");
            exampleRow.createCell(4).setCellValue("白色");
            exampleRow.createCell(5).setCellValue("公司停车场");
            exampleRow.createCell(6).setCellValue("LVSHCAMB1CE054967");
            exampleRow.createCell(7).setCellValue("EA211358975");
            exampleRow.createCell(8).setCellValue("150000");
            exampleRow.createCell(9).setCellValue("5000");
            exampleRow.createCell(10).setCellValue("2023-01-01");
            exampleRow.createCell(11).setCellValue("2023-01-15");
            exampleRow.createCell(12).setCellValue("2024-01-01");
            exampleRow.createCell(13).setCellValue("2024-06-01");
            exampleRow.createCell(14).setCellValue("1");
            exampleRow.createCell(15).setCellValue("新购车辆");
            
            // 添加说明行
            Row noteRow = sheet.createRow(2);
            Cell noteCell = noteRow.createCell(0);
            noteCell.setCellValue("注意：带*的列为必填项，状态值：1=正常使用，2=维修中，3=停用，0=报废，日期格式：YYYY-MM-DD");
            CellStyle noteStyle = workbook.createCellStyle();
            Font noteFont = workbook.createFont();
            noteFont.setColor(IndexedColors.RED.getIndex());
            noteStyle.setFont(noteFont);
            noteCell.setCellStyle(noteStyle);
            
            // 合并单元格用于显示注释
            sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(2, 2, 0, 15));
            
            // 自动调整列宽
            for (int i = 0; i < columns.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 将工作簿写入字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();
            
            // 生成文件名
            String filename = "vehicle_import_template.xlsx";
            
            // 返回Excel文件
            ByteArrayResource resource = new ByteArrayResource(outputStream.toByteArray());
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
                    .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                    .contentLength(resource.contentLength())
                    .body(resource);
            
        } catch (IOException e) {
            System.err.println("生成车辆导入模板失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 导入车辆数据
     */
    @PostMapping("/import")
    @OperationLogAnnotation(module = "车辆管理", operationType = 2, description = "导入车辆数据")
    public R<Map<String, Object>> importVehicles(@RequestParam("file") MultipartFile file) {
        System.out.println("接收到导入车辆数据请求，文件名: " + file.getOriginalFilename());
        
        if (file.isEmpty()) {
            return R.error("请选择要导入的文件");
        }
        
        // 检查文件格式
        String fileName = file.getOriginalFilename();
        if (fileName == null || !(fileName.endsWith(".xlsx") || fileName.endsWith(".xls"))) {
            return R.error("请上传Excel文件(.xlsx或.xls)");
        }
        
        try {
            // 读取Excel文件
            Workbook workbook;
            if (fileName.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(file.getInputStream());
            } else {
                workbook = new HSSFWorkbook(file.getInputStream());
            }
            
            Sheet sheet = workbook.getSheetAt(0);
            
            // 跳过标题行和说明行，从第2行开始读取数据
            int startRow = 1;
            int totalRows = sheet.getPhysicalNumberOfRows();
            
            List<Vehicle> vehicles = new ArrayList<>();
            Map<String, Object> result = new HashMap<>();
            int successCount = 0;
            int failCount = 0;
            List<String> errors = new ArrayList<>();
            
            for (int i = startRow; i < totalRows; i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                
                // 如果是注释行或空行，跳过
                Cell firstCell = row.getCell(0);
                if (firstCell == null || firstCell.getCellType() == CellType.BLANK || 
                    (firstCell.getCellType() == CellType.STRING && firstCell.getStringCellValue().startsWith("注意"))) {
                    continue;
                }
                
                try {
                    Vehicle vehicle = new Vehicle();
                    
                    // 读取车牌号（必填）
                    Cell plateNumberCell = row.getCell(0);
                    if (plateNumberCell == null || plateNumberCell.getCellType() == CellType.BLANK) {
                        errors.add("第" + (i+1) + "行：车牌号不能为空");
                        failCount++;
                        continue;
                    }
                    String plateNumber = plateNumberCell.getStringCellValue().trim();
                    vehicle.setPlateNumber(plateNumber);
                    
                    // 读取车辆类型（必填）
                    Cell vehicleTypeCell = row.getCell(1);
                    if (vehicleTypeCell == null || vehicleTypeCell.getCellType() == CellType.BLANK) {
                        errors.add("第" + (i+1) + "行：车辆类型不能为空");
                        failCount++;
                        continue;
                    }
                    vehicle.setVehicleType(vehicleTypeCell.getStringCellValue().trim());
                    
                    // 读取品牌（必填）
                    Cell brandCell = row.getCell(2);
                    if (brandCell == null || brandCell.getCellType() == CellType.BLANK) {
                        errors.add("第" + (i+1) + "行：品牌不能为空");
                        failCount++;
                        continue;
                    }
                    vehicle.setBrand(brandCell.getStringCellValue().trim());
                    
                    // 读取型号（选填）
                    Cell modelCell = row.getCell(3);
                    if (modelCell != null && modelCell.getCellType() != CellType.BLANK) {
                        vehicle.setModel(modelCell.getStringCellValue().trim());
                    }
                    
                    // 读取颜色（选填）
                    Cell colorCell = row.getCell(4);
                    if (colorCell != null && colorCell.getCellType() != CellType.BLANK) {
                        vehicle.setColor(colorCell.getStringCellValue().trim());
                    }
                    
                    // 读取位置（选填）
                    Cell locationCell = row.getCell(5);
                    if (locationCell != null && locationCell.getCellType() != CellType.BLANK) {
                        vehicle.setLocation(locationCell.getStringCellValue().trim());
                    }
                    
                    // 读取车架号（选填）
                    Cell frameNumberCell = row.getCell(6);
                    if (frameNumberCell != null && frameNumberCell.getCellType() != CellType.BLANK) {
                        vehicle.setFrameNumber(frameNumberCell.getStringCellValue().trim());
                    }
                    
                    // 读取发动机号（选填）
                    Cell engineNumberCell = row.getCell(7);
                    if (engineNumberCell != null && engineNumberCell.getCellType() != CellType.BLANK) {
                        vehicle.setEngineNumber(engineNumberCell.getStringCellValue().trim());
                    }
                    
                    // 读取购买价格（选填）
                    Cell priceCell = row.getCell(8);
                    if (priceCell != null && priceCell.getCellType() != CellType.BLANK) {
                        if (priceCell.getCellType() == CellType.NUMERIC) {
                            vehicle.setPurchasePrice(priceCell.getNumericCellValue());
                        } else if (priceCell.getCellType() == CellType.STRING) {
                            try {
                                vehicle.setPurchasePrice(Double.parseDouble(priceCell.getStringCellValue().trim()));
                            } catch (NumberFormatException e) {
                                errors.add("第" + (i+1) + "行：购买价格格式不正确");
                            }
                        }
                    }
                    
                    // 读取当前里程（选填）
                    Cell mileageCell = row.getCell(9);
                    if (mileageCell != null && mileageCell.getCellType() != CellType.BLANK) {
                        if (mileageCell.getCellType() == CellType.NUMERIC) {
                            vehicle.setCurrentMileage(mileageCell.getNumericCellValue());
                        } else if (mileageCell.getCellType() == CellType.STRING) {
                            try {
                                vehicle.setCurrentMileage(Double.parseDouble(mileageCell.getStringCellValue().trim()));
                            } catch (NumberFormatException e) {
                                errors.add("第" + (i+1) + "行：当前里程格式不正确");
                            }
                        }
                    }
                    
                    // 读取购买日期（选填）
                    Cell purchaseDateCell = row.getCell(10);
                    if (purchaseDateCell != null && purchaseDateCell.getCellType() != CellType.BLANK) {
                        try {
                            if (purchaseDateCell.getCellType() == CellType.NUMERIC) {
                                vehicle.setPurchaseDate(purchaseDateCell.getLocalDateTimeCellValue());
                            } else if (purchaseDateCell.getCellType() == CellType.STRING) {
                                String dateStr = purchaseDateCell.getStringCellValue().trim();
                                vehicle.setPurchaseDate(LocalDate.parse(dateStr).atStartOfDay());
                            }
                        } catch (Exception e) {
                            errors.add("第" + (i+1) + "行：购买日期格式不正确，应为YYYY-MM-DD");
                        }
                    }
                    
                    // 读取登记日期（选填）
                    // 注意：Vehicle实体中没有registrationDate字段，这里跳过处理
                    
                    // 读取保险到期日（选填）
                    // 注意：Vehicle实体中没有insuranceExpiry字段，这里跳过处理
                    
                    // 读取年检到期日（选填）
                    // 注意：Vehicle实体中没有inspectionExpiry字段，这里跳过处理
                    
                    // 读取状态（必填）
                    Cell statusCell = row.getCell(14);
                    if (statusCell == null || statusCell.getCellType() == CellType.BLANK) {
                        errors.add("第" + (i+1) + "行：状态不能为空");
                        failCount++;
                        continue;
                    }
                    
                    Integer status = null;
                    if (statusCell.getCellType() == CellType.NUMERIC) {
                        status = (int) statusCell.getNumericCellValue();
                    } else if (statusCell.getCellType() == CellType.STRING) {
                        try {
                            status = Integer.parseInt(statusCell.getStringCellValue().trim());
                        } catch (NumberFormatException e) {
                            errors.add("第" + (i+1) + "行：状态必须是数字(0-3)");
                            failCount++;
                            continue;
                        }
                    }
                    
                    if (status == null || status < 0 || status > 3) {
                        errors.add("第" + (i+1) + "行：状态值无效，必须是0-3之间的数字");
                        failCount++;
                        continue;
                    }
                    vehicle.setStatus(status);
                    
                    // 读取备注（选填）
                    Cell remarkCell = row.getCell(15);
                    if (remarkCell != null && remarkCell.getCellType() != CellType.BLANK) {
                        vehicle.setRemark(remarkCell.getStringCellValue().trim());
                    }
                    
                    // 检查车牌号是否已存在
                    if (vehicleService.existsActiveVehicleWithPlateNumber(plateNumber)) {
                        errors.add("第" + (i+1) + "行：车牌号 " + plateNumber + " 已存在且未被删除，不能重复添加");
                        failCount++;
                        continue;
                    }
                    
                    // 添加到列表
                    vehicles.add(vehicle);
                    successCount++;
                    
                } catch (Exception e) {
                    errors.add("第" + (i+1) + "行：处理失败，原因：" + e.getMessage());
                    failCount++;
                }
            }
            
            workbook.close();
            
            // 批量保存车辆数据
            if (!vehicles.isEmpty()) {
                vehicleService.batchAddVehicles(vehicles);
            }
            
            // 返回导入结果
            result.put("total", successCount + failCount);
            result.put("success", successCount);
            result.put("fail", failCount);
            result.put("errors", errors);
            
            return R.ok(result);
            
        } catch (Exception e) {
            System.err.println("导入车辆数据失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("导入失败：" + e.getMessage());
        }
    }
} 